package com.woyou.service.receiver;

import org.androidannotations.annotations.EBean;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import cn.jpush.android.api.JPushInterface;

import com.woyou.Constant;
import com.woyou.bean.Info;
import com.woyou.bean.MyOrderItem;
import com.woyou.ui.activity.ActivitiesActivity_;
import com.woyou.ui.activity.HomeActivityPresenter_;
import com.woyou.ui.activity.HomeActivity_;
import com.woyou.ui.activity.orderdetail.OrderDetailActivity;
import com.woyou.utils.Utils;
import com.woyou.utils.eventbus.EventClearShoppingCar;
import com.woyou.utils.eventbus.EventRestConfirm;

import de.greenrobot.event.EventBus;

/**
 * 自定义接收器
 * 
 * 如果不定义这个 Receiver，则：
 * 1) 默认用户会打开主界面
 * 2) 接收不到自定义消息
 */
@EBean
public class JPushReceiver extends BroadcastReceiver {
	
	private static final String TAG = "JPushReceiver";
	private String title;
	private String message;
	private Context mContext;
	private Intent msgIntent;
	private Bundle bundle;
	
	@Override
	public void onReceive(Context context, Intent intent) {
		mContext = context;
		bundle = intent.getExtras();
		Log.d(TAG, "[JPushReceiver] onReceive - " + intent.getAction() + ", extras: " + printBundle(bundle));
		
        if (JPushInterface.ACTION_REGISTRATION_ID.equals(intent.getAction())) {
            String regId = bundle.getString(JPushInterface.EXTRA_REGISTRATION_ID);
            Log.d(TAG, "[JPushReceiver] 接收Registration Id : " + regId);
            //send the Registration Id to your server...
            
        } else if (JPushInterface.ACTION_MESSAGE_RECEIVED.equals(intent.getAction())) {
        	Log.d(TAG, "[JPushReceiver] 接收到推送下来的自定义消息: " + bundle.getString(JPushInterface.EXTRA_MESSAGE));
        	
        } else if (JPushInterface.ACTION_NOTIFICATION_RECEIVED.equals(intent.getAction())) {
            Log.d(TAG, "[JPushReceiver] 接收到推送下来的通知");
            int notifactionId = bundle.getInt(JPushInterface.EXTRA_NOTIFICATION_ID);
            Log.d(TAG, "[JPushReceiver] 接收到推送下来的通知的ID: " + notifactionId);
            
            String msg = bundle.getString(JPushInterface.EXTRA_ALERT);
            if ( msg.contains("[O:") || msg.contains("[o:") ){
            	// 收到推送通知,发送广播,刷新订单详情
            	// Itent就是我们要发送的内容
            	Intent brocast = new Intent(); 
            	// 设置你这个广播的action，只有和这个action一样的接受者才能接受者才能接收广播
            	brocast.setAction("com.woyou.ORDERDETAIL.UPDATE"); 
            	// 发送广播
            	context.sendBroadcast(brocast);  						
            }
            
        } else if (JPushInterface.ACTION_NOTIFICATION_OPENED.equals(intent.getAction())) {
            Log.d(TAG, "[JPushReceiver] 用户点击打开了通知");
            JPushInterface.reportNotificationOpened(context, bundle.getString(JPushInterface.EXTRA_MSG_ID));
            if(Utils.isBackgroundRunning(context)){
            	// 打开自定义的Activity
            	Log.d(TAG, "[JPushReceiver] 打开Activity");
            	Intent i = new Intent(context, HomeActivity_.class);
            	i.putExtras(bundle);
            	i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP);
            	context.startActivity(i);
            	mHandler.sendEmptyMessage(SEND_BROADCAST);
            	
            }else{
            	processCustomUI(context, bundle);
            }
			// 重置购物车和确认订单
			EventBus.getDefault().post(new EventClearShoppingCar());
			EventBus.getDefault().post(new EventRestConfirm());
        } else if (JPushInterface.ACTION_RICHPUSH_CALLBACK.equals(intent.getAction())) {
            Log.d(TAG, "[JPushReceiver] 用户收到到RICH PUSH CALLBACK: " + bundle.getString(JPushInterface.EXTRA_EXTRA));
            //在这里根据 JPushInterface.EXTRA_EXTRA 的内容处理代码，比如打开新的Activity， 打开一个网页等..
           
        } else if(JPushInterface.ACTION_CONNECTION_CHANGE.equals(intent.getAction())) {
        	boolean connected = intent.getBooleanExtra(JPushInterface.EXTRA_CONNECTION_CHANGE, false);
        	Log.e(TAG, "[JPushReceiver]" + intent.getAction() +" connected state change to "+connected);
        	  
        } else {
        	Log.d(TAG, "[JPushReceiver] Unhandled intent - " + intent.getAction());
        }
	}

	// 打印所有的 intent extra 数据
	private static String printBundle(Bundle bundle) {
		StringBuilder sb = new StringBuilder();
		for (String key : bundle.keySet()) {
			if (key.equals(JPushInterface.EXTRA_NOTIFICATION_ID)) {
				sb.append("\nkey:" + key + ", value:" + bundle.getInt(key));
			}else if(key.equals(JPushInterface.EXTRA_CONNECTION_CHANGE)){
				sb.append("\nkey:" + key + ", value:" + bundle.getBoolean(key));
			} 
			else {
				sb.append("\nkey:" + key + ", value:" + bundle.getString(key));
			}
		}
		return sb.toString();
	}
	
	// send msg to UI(MessageReceiver)
	private void processCustomUI(Context context, Bundle bundle) {
		String msg = bundle.getString(JPushInterface.EXTRA_ALERT);
		if ( msg.contains("[O:") || msg.contains("[o:") ) {			
			// 进入订单详情
			String info = "";
			String oId = "";
			if ( msg.contains("[O:") ) {
				try {
					int index1 = msg.indexOf("[O:");
					int index2 = msg.indexOf("]");
					info = msg.substring(0, index1);
					oId = msg.substring(index1+3, index2);
				} catch (Exception e) {
					e.printStackTrace();
				}
			} else {
				try {
					int index1 = msg.indexOf("[o:");
					int index2 = msg.indexOf("]");
					info = msg.substring(0, index1);
					oId = msg.substring(index1+3, index2);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			Log.i(TAG, "oId:=" + oId);
			MyOrderItem order = new MyOrderItem();
			order.setInfo(info);
			order.setoId(oId);
			Info<MyOrderItem> inf = new Info<MyOrderItem>(order, JPushReceiver_.class);
			openActivity(context, OrderDetailActivity.class, inf);
			
		} else if ( msg.contains("[U:") || msg.contains("[u:") ) {  
			// 打开活动页面
			String url = "";
			if ( msg.contains("[U:") ) {
				try {
					int index1 = msg.indexOf("[U:");
					int index2 = msg.indexOf("]");
					url = msg.substring(index1+3, index2);
				} catch (Exception e) {
					e.printStackTrace();
				}
			} else {
				try {
					int index1 = msg.indexOf("[u:");
					int index2 = msg.indexOf("]");
					url = msg.substring(index1+3, index2);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			Log.i(TAG, "url:=" + url);
			Info<String> info = new Info<String>(url, JPushReceiver_.class);
			Utils.openActivity(context, ActivitiesActivity_.class, info);
		} 
		
    }
	
	private static final int SEND_BROADCAST = 0x0001;
	@SuppressLint("HandlerLeak")
	private Handler mHandler = new Handler(){
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case SEND_BROADCAST:
				HomeActivity_.isShow = false;
				System.out.println("1==="+HomeActivity_.isShow);
				if(HomeActivityPresenter_.getInstance_(mContext).isAlive()){
           		    processCustomUI(mContext, bundle);
           	    }else{
           	    	sendEmptyMessageDelayed(SEND_BROADCAST, 1000);
           	    }
				break;

			default:
				break;
			}
		};
	};
	
	@SuppressWarnings("rawtypes")
	public static void openActivity(Context context, Class clazz, Info info) {
		Intent intent = new Intent();
		intent.setClass(context, clazz);
		intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);  
		if (info != null) {
			intent.putExtra(Constant.INFO_NAME, info);
		}
		context.startActivity(intent);

	}
	
	
}
